from django.conf import settings
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from fdfs_client.client import Fdfs_client


@deconstructible
class FastDFSStorage(Storage):
    def __init__(self, fastdfs_conf=None, base_url=None):

        if fastdfs_conf is None:
            fastdfs_conf = settings.FASTDFS_CONF
        self.fastdfs_conf = fastdfs_conf
        if base_url is None:
            base_url = settings.BASE_URL
        self.base_url = base_url

    def open(self, name, mode='rb'):

        pass

    def _save(self, name, content):

        client = Fdfs_client(self.fastdfs_conf)

        filed_id = client.upload_appender_by_buffer(content.read())
        if filed_id['Status'] != 'Upload successed.':
            raise Exception('upload error')

        return filed_id['Remote file_id']

    def url(self, name):

        return self.base_url + name

    def exists(self, name):

        return False
